<template>
  <div class="change-requirement">
    <el-container>
      <el-header class="header-class" height="22">
        <div class="header-text">Change Requirement</div>
      </el-header>
      <el-main class="container-main">
        <el-form :validate-on-rule-change="false" label-position="left" :model="changeRequirementData" :rules="rules"
                 ref="validatorForm" :size="form_size" :label-width="label_width" :show-message="false">
          <el-form-item label="Change Main Category :" prop="changeMainCategory">
            <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                             :labelName="changeRequirementData.changeMainCategory">
              <el-select v-model="changeRequirementData.changeMainCategory" placeholder="select"
                         @change="onChangeSelected">
                <el-option
                  v-for="category in changeRequirementData.changeMainCategoryList"
                  :key="category.categoryName"
                  :label="category.categoryName"
                  :value="category">
                </el-option>
              </el-select>
            </permission-slot>
          </el-form-item>

          <el-form-item label="Change Sub Category :" prop="changeSubCategory">
            <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                             :labelName="changeRequirementData.changeSubCategory">
              <el-select v-model="changeRequirementData.changeSubCategory" placeholder="select"
                         @change="onChangeSubCategory">
                <el-option
                  v-for="subCategory in changeRequirementData.changeSubCategoryList"
                  :key="subCategory.subcategoryName"
                  :label="subCategory.subcategoryName"
                  :value="subCategory.subCategoryID">
                </el-option>
              </el-select>
            </permission-slot>
          </el-form-item>

          <el-form-item label="Production Platform Involve :" prop="productionPlatformInvolve">
            <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                             :labelName="changeRequirementData.productionPlatformInvolve">
              <el-input style="width: 660px" v-model="changeRequirementData.productionPlatformInvolve"></el-input>
            </permission-slot>
          </el-form-item>

          <el-form-item label="Expected Date Change (HKT) :" ref="expectedDateChange" prop="expectedDateChange">
            <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                             :labelName="readOnlyExpectedDate">
              <el-date-picker style="width: 200px" type="date" :clearable="false" placeholder="select date"
                              v-model="changeRequirementData.expectedDateChange"></el-date-picker>
            </permission-slot>
          </el-form-item>

          <el-form-item label="Expected Time Change (HKT) :" prop="expectedTimeChange">
            <permission-slot style="display: inline-block" :readOnly="!this.functionList.update_change_reqirement"
                             :labelName="changeRequirementData.expectedTimeChange.hours">
              <el-select style="width: 88px" v-model="changeRequirementData.expectedTimeChange.hours"
                         placeholder="select">
                <el-option
                  v-for="item in times"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </permission-slot>
            <span class="between-space"> : </span>
            <permission-slot style="display: inline-block" :readOnly="!this.functionList.update_change_reqirement"
                             :labelName="changeRequirementData.expectedTimeChange.minutes">
              <el-select style="width: 88px" v-model="changeRequirementData.expectedTimeChange.minutes"
                         placeholder="select">
                <el-option
                  v-for="item in hours"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </permission-slot>
            <span class="comment_style">(hh:mm)</span>
          </el-form-item>

          <el-form-item label="PIDC Submission Link for Reference :">
            <a href="http://hkgpidc/pidc/Login.jsp">http://hkgpidc/pidc/Login.jsp</a>
          </el-form-item>

          <el-form-item label="For SecAdmin Reference :">
            <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                             :labelName="changeRequirementData.secAdminReference">
              <el-input style="width: 660px;" v-model="changeRequirementData.secAdminReference"></el-input>
            </permission-slot>
          </el-form-item>

          <el-form-item label="Online Service Impact :">
            <el-col :span="12">
              <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                               :labelName="changeRequirementData.isOnlineService">
                <el-radio v-model="changeRequirementData.isOnlineService" label="No">No</el-radio>
                <el-radio v-model="changeRequirementData.isOnlineService" label="Yes">Yes</el-radio>
                <span
                  class="comment_style">(if yes, please specify unavailable period and Global/Regional user impact)</span>
              </permission-slot>
              <div v-show="changeRequirementData.isOnlineService === 'Yes'">
                <el-row>
                  <div style="float: left;">
                    <el-form-item prop="onlineServiceImpactFromDate">
                      <permission-slot style="display: inline-block;"
                                       :readOnly="!this.functionList.update_change_reqirement"
                                       :labelName="readOnlyOnlineServiceImpactFromDate">
                        <el-date-picker :clearable="false" type="date" placeholder="select date"
                                        v-model="changeRequirementData.onlineServiceImpact.fromDate"></el-date-picker>
                      </permission-slot>
                    </el-form-item>
                  </div>
                  <span class="between-space" style="float: left"> - </span>
                  <div style="float: left; width: 200px">
                    <el-form-item prop="onlineServiceImpactToDate">
                      <permission-slot style="display: inline-block"
                                       :readOnly="!this.functionList.update_change_reqirement"
                                       :labelName="readOnlyOnlineServiceImpactToDate">
                        <el-date-picker :clearable="false" type="date" placeholder="select date"
                                        v-model="changeRequirementData.onlineServiceImpact.toDate"></el-date-picker>
                      </permission-slot>
                    </el-form-item>
                  </div>
                </el-row>
                <el-row>
                  <el-form-item prop="onlineServiceImpactDescription">
                    <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                                     :labelName="changeRequirementData.onlineServiceImpactDescription">
                      <el-input type="textarea" v-model="changeRequirementData.onlineServiceImpactDescription"
                                class="text_area_input"></el-input>
                    </permission-slot>
                  </el-form-item>
                </el-row>
              </div>
            </el-col>
          </el-form-item>

          <el-form-item label="Backend Application/Function Impact :" prop="isBackendApplication">
            <el-col :span="12">
              <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                               :labelName="changeRequirementData.isBackendApplication">
                <el-radio v-model="changeRequirementData.isBackendApplication" label="No">No</el-radio>
                <el-radio v-model="changeRequirementData.isBackendApplication" label="Yes">Yes</el-radio>
                <span
                  class="comment_style">(if yes, please specify unavailable period and Global/Regional user impact)</span>
              </permission-slot>
            </el-col>
          </el-form-item>
          <el-form-item prop="backendApplicationFunctionImpactDescription"
                        v-show="changeRequirementData.isBackendApplication === 'Yes'">
            <el-row>
              <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                               :labelName="changeRequirementData.backendApplicationFunctionImpactDescription">
                <el-input type="textarea" v-model="changeRequirementData.backendApplicationFunctionImpactDescription"
                          class="text_area_input"></el-input>
              </permission-slot>
            </el-row>
          </el-form-item>

          <el-form-item label="System / Platform Impact :" prop="isSystemPlatform2">
            <el-col :span="12">
              <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                               :labelName="changeRequirementData.isSystemPlatform">
                <el-radio v-model="changeRequirementData.isSystemPlatform" label="No">No</el-radio>
                <el-radio v-model="changeRequirementData.isSystemPlatform" label="Yes">Yes</el-radio>
                <span class="comment_style">(if yes, please specify)</span>
              </permission-slot>
            </el-col>
          </el-form-item>
          <el-form-item prop="systemPlatformImpactDescription"
                        v-show="changeRequirementData.isSystemPlatform === 'Yes'">
            <el-row>
              <permission-slot :readOnly="!this.functionList.update_change_reqirement"
                               :labelName="changeRequirementData.systemPlatformImpactDescription">
                <el-input type="textarea" v-model="changeRequirementData.systemPlatformImpactDescription"
                          class="text_area_input"></el-input>
              </permission-slot>
            </el-row>
          </el-form-item>

          <el-form-item prop="riskLevel" label="Risk Level :" v-show="changeRequirementData.isRiskLevel === true">
            <permission-slot
              :readOnly="!functionList.edit_change_control_teams_reference && compareStatusManagementData.pcrsStatusValue !== 'Pending'"
              :labelName="changeRequirementData.riskLevel">
              <el-radio v-model="changeRequirementData.riskLevel" label="High">High(27)</el-radio>
              <el-radio v-model="changeRequirementData.riskLevel" label="Medium">Medium(3-18)</el-radio>
              <el-radio v-model="changeRequirementData.riskLevel" label="Low">Low(1-2)</el-radio>
              <span class="comment_style">(for Low,no Risk Assessment is needed)</span>
            </permission-slot>
            <el-row>
              <span>Risk Level calculation method:</span>
              <a href="http://i2isd/sites/PPA/ChgMan/Change%20Procedure/RiskLevelCalculationMethod.doc">http://i2isd/sites/PPA/ChgMan/Change%20Procedure/RiskLevelCalculationMethod.doc</a>
            </el-row>
            <span class="highlight_style">Please supplement risk calculation [(IM) x (LK) x (CM)] rating to your team leader to review your change if it's for a 'High' or 'Medium' risk change.</span>
            <el-row v-show="changeRequirementData.riskLevel === 'High' || changeRequirementData.riskLevel === 'Medium'">
              <permission-slot
                :readOnly="!functionList.edit_change_control_teams_reference && compareStatusManagementData.pcrsStatusValue !== 'Pending'"
                :labelName="changeRequirementData.riskAssessment">
                <el-input type="textarea" v-model="changeRequirementData.riskAssessment"
                          placeholder="Example:(IM) x (LK) x (CM)" class="text_area_input"></el-input>
              </permission-slot>
            </el-row>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import categoryService from '@/service/category'
import permissionSlot from '@/base-components/permission/PermissionSlot.vue'
import moment from 'moment'
import _ from 'lodash'

export default {
  components: {
    permissionSlot
  },
  props: {
    changeRequirementData: {
      type: Object
    },
    compareSubmissionDetailData: {
      type: Object
    },
    compareStatusManagementData: {
      type: Object
    },
    functionList: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  computed: {
    readOnlyExpectedDate() {
      return moment(this.changeRequirementData.expectedDateChange).format('YYYY-MM-DD')
    },
    readOnlyOnlineServiceImpactFromDate() {
      return moment(this.changeRequirementData.onlineServiceImpact.fromDate).format('YYYY-MM-DD')
    },
    readOnlyOnlineServiceImpactToDate() {
      return moment(this.changeRequirementData.onlineServiceImpact.toDate).format('YYYY-MM-DD')
    }
  },
  data() {
    let validateExpectedDate = (rule, value, callback) => {
      let selectedExceptedDate = moment(this.changeRequirementData.expectedDateChange)
      let impactFromDate = moment(this.changeRequirementData.onlineServiceImpact.fromDate)

      if (!value) {
        callback(new Error())
      } else if (moment().subtract({days: 1}).isAfter(selectedExceptedDate)) {
        this.$message({showClose: true, message: 'expected date should after current day', type: 'error'})
        callback(new Error())
      } else if (!this.compareSubmissionDetailData.typeOfChange) {
        this.$message({showClose: true, message: 'Type Of Change Can not be null', type: 'error'})
        callback(new Error())
      } else if (this.compareSubmissionDetailData.typeOfChange === 'Planned' && moment().add(1, 'days').isAfter(selectedExceptedDate)) {
        this.$message({
          showClose: true,
          message: 'expected date should after 2 days when select planned',
          type: 'error'
        })
        callback(new Error())
      } else if (this.compareSubmissionDetailData.typeOfChange === 'Un-planned' && !this.compareSubmissionDetailData.TTNo && !this.compareSubmissionDetailData.relatedPCRS) {
        this.$message({showClose: true, message: 'TT No cannot be blank', type: 'error'})
        callback(new Error())
      } else if (impactFromDate && impactFromDate.isBefore(selectedExceptedDate) && this.changeRequirementData.isOnlineService === 'Yes') {
        this.$message({showClose: true, message: 'selectedExceptedDate should before impactFromDate', type: 'error'})
        callback(new Error())
      } else {
        callback()
      }
    }

    let validateTimeChange = (rule, value, callback) => {
      let hours = this.changeRequirementData.expectedTimeChange.hours
      let minutes = this.changeRequirementData.expectedTimeChange.minutes
      if (hours === '') {
        callback(new Error('expected_time_change_hours'))
      } else if (minutes === '') {
        callback(new Error('expected_time_change_minutes'))
      } else {
        callback()
      }
    }

    let validateRiskLevel = (rule, value, callback) => {
      if (this.changeRequirementData.isRiskLevel) {
        let riskLevel = this.changeRequirementData.riskLevel
        let riskCalculation = this.changeRequirementData.riskAssessment
        if (riskLevel === '') {
          this.$message({showClose: true, message: 'Risk Level cannot be blank', type: 'error'})
          callback(new Error())
        } else if ((riskLevel === 'High' || riskLevel === 'Medium') && !riskCalculation) {
          this.$message({showClose: true, message: 'Risk Assessment cannot be blank', type: 'error'})
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    let validateOnlineServiceImpactFromDate = (rule, value, callback) => {
      if (this.changeRequirementData.isOnlineService === 'Yes' && this.checkDateOnce === true) {
        let expectedDate = this.changeRequirementData.expectedDateChange
        let onlineServiceFromDate = this.changeRequirementData.onlineServiceImpact.fromDate
        let onlineServiceToDate = this.changeRequirementData.onlineServiceImpact.toDate
        let currentDate = new Date(new Date().getTime() - 24 * 60 * 60 * 1000)

        if (currentDate > onlineServiceFromDate) {
          this.$message({showClose: true, message: 'OnlineService From Date must after Current Date', type: 'error'})
          callback(new Error('error'))
        } else if (onlineServiceFromDate < expectedDate) {
          this.$message({showClose: true, message: 'OnlineService From Date must after Expected Date', type: 'error'})
          callback(new Error('error'))
        } else if (onlineServiceFromDate !== '' && onlineServiceToDate !== '' && onlineServiceFromDate > onlineServiceToDate) {
          this.$message({showClose: true, message: 'OnlineService From Date must before To Date', type: 'error'})
          callback(new Error('error'))
        } else {
          callback()
        }
        this.checkDateOnce = false
        this.$refs['validatorForm'].validateField('onlineServiceImpactToDate')
        this.$refs['validatorForm'].validateField('expectedDateChange')
      } else {
        callback()
        this.checkDateOnce = true
      }
    }

    let validateOnlineServiceImpactToDate = (rule, value, callback) => {
      if (this.changeRequirementData.isOnlineService === 'Yes' && this.checkDateOnce === true) {
        let expectedDate = this.changeRequirementData.expectedDateChange
        let onlineServiceFromDate = this.changeRequirementData.onlineServiceImpact.fromDate
        let onlineServiceToDate = this.changeRequirementData.onlineServiceImpact.toDate
        let currentDate = new Date(new Date().getTime() - 24 * 60 * 60 * 1000)

        if (currentDate > onlineServiceToDate) {
          this.$message({showClose: true, message: 'OnlineService To Date must after Current Date', type: 'error'})
          callback(new Error('error'))
        } else if (onlineServiceFromDate < expectedDate) {
          this.$message({showClose: true, message: 'OnlineService To Date must after Expected Date', type: 'error'})
          callback(new Error())
        } else if (onlineServiceFromDate !== '' && onlineServiceToDate !== '' && onlineServiceFromDate > onlineServiceToDate) {
          this.$message({showClose: true, message: 'OnlineService To Date must after From Date', type: 'error'})
          callback(new Error())
        } else {
          callback()
        }
        this.checkDateOnce = false
        this.$refs['validatorForm'].validateField('onlineServiceImpactFromDate')
        this.$refs['validatorForm'].validateField('expectedDateChange')
      } else {
        callback()
        this.checkDateOnce = true
      }
    }

    let validateSystemPlatformImpactDescription = (rule, value, callback) => {
      if (this.changeRequirementData.isSystemPlatform === 'Yes') {
        if (value === '') {
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    let validateBackendApplicationFunctionImpactDescription = (rule, value, callback) => {
      if (this.changeRequirementData.isBackendApplication === 'Yes') {
        if (value === '') {
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    let validateOnlineServiceImpactDescription = (rule, value, callback) => {
      if (this.changeRequirementData.isOnlineService === 'Yes') {
        if (!value) {
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      checkDateOnce: true,
      form_size: 'mini',
      label_width: '325px',
      times: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'],
      hours: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59'],
      time_value: '',

      rules: {
        changeMainCategory: [
          {required: true, message: 'changeMainCategory', trigger: 'change'}
        ],
        changeSubCategory: [
          {required: true, message: 'changeSubCategory', trigger: 'change'}
        ],
        productionPlatformInvolve: [
          {required: true, message: 'productionPlatformInvolve', trigger: 'change'}
        ],
        expectedDateChange: [
          {required: true, validator: validateExpectedDate, trigger: 'change'}
        ],
        expectedTimeChange: [
          {required: true, validator: validateTimeChange, trigger: 'change'}
        ],
        systemPlatformImpactDescription: [
          {validator: validateSystemPlatformImpactDescription}
        ],
        backendApplicationFunctionImpactDescription: [
          {validator: validateBackendApplicationFunctionImpactDescription}
        ],
        onlineServiceImpactDescription: [
          {validator: validateOnlineServiceImpactDescription}
        ],
        onlineServiceImpactFromDate: [
          {validator: validateOnlineServiceImpactFromDate, trigger: 'change'}
        ],
        onlineServiceImpactToDate: [
          {validator: validateOnlineServiceImpactToDate, trigger: 'change'}
        ],
        riskLevel: [
          {required: true, validator: validateRiskLevel, trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.initCategoriesList()
  },
  methods: {
    onChangeSelected(category) {
      this.changeRequirementData.changeSubCategory = ''
      this.changeRequirementData.isRiskLevel = false
      this.changeRequirementData.changeMainCategory = category.categoryName
      this.changeRequirementData.changeSubCategoryList = category.subCategory
    },
    onChangeSubCategory(subCategory) {
      let index = _.findIndex(this.changeRequirementData.changeSubCategoryList, function (o) { return o.subCategoryID === subCategory })
      this.changeRequirementData.isRiskLevel = this.changeRequirementData.changeSubCategoryList[index].riskLevel
    },
    async initCategoriesList() {
      this.changeRequirementData.changeMainCategoryList = await categoryService.findAllCategories()
      if (this.changeRequirementData.changeMainCategory) {
        let $this = this
        let index = _.findIndex(this.changeRequirementData.changeMainCategoryList, function (mainCategory) {
          return mainCategory.categoryId === $this.changeRequirementData.changeMainCategory
        })
        this.changeRequirementData.changeSubCategoryList = this.changeRequirementData.changeMainCategoryList[index].subCategory
      }
    }
  }
}
</script>

<style scoped lang="scss">
  @import './../../../common/css/base.scss';

  .container-main {
    border: 1px solid $base-header-color;
  }

  .header-class {
    @include baseHeader(30px);
  }

  .header-text {
    color: #fff;
    margin-top: 5px;
    font-weight: bold;
  }

  .input-height {
    height: 20px;
  }

  .el-form-item {
    margin-bottom: 10px;
  }

  .comment_style {
    margin-left: 10px;
    color: #666;
  }

  .between-space {
    margin: 0 6px;
  }

  .highlight_style {
    color: red;
  }

  .text_area_input {
    margin-bottom: 5px;
    width: 660px;
  }

  .edit-date {
    width: 200px;
  }

</style>
